"""认证工具函数"""

from fastapi import HTTPException, status
from sqlalchemy.orm import Session

from src.auth.jwt import verify_password, get_password_hash
from src.models.user import User
from schemas import ChangePasswordRequest


def change_user_password(
    db: Session,
    current_user: User,
    change_password_data: ChangePasswordRequest
) -> bool:
    """
    修改用户密码
    
    Args:
        db: 数据库会话
        current_user: 当前用户对象
        change_password_data: 修改密码请求数据
        
    Returns:
        bool: 密码修改是否成功
        
    Raises:
        HTTPException: 当原密码错误或新密码不符合要求时抛出异常
    """
    # 验证当前密码是否正确
    if not verify_password(change_password_data.current_password, current_user.password_hash):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前密码错误"
        )
    
    # 检查新密码是否与原密码相同
    if change_password_data.current_password == change_password_data.new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="新密码不能与当前密码相同"
        )
    
    # 更新密码
    current_user.password_hash = get_password_hash(change_password_data.new_password)
    db.commit()
    
    return True